package master;

/**
 * @author chenyw
 * @date 2022/7/23 17:39
 */
public class M23MergeKLists {
    public ListNode mergeKLists(ListNode[] lists) {
        int n = lists.length;
        return dfs(lists, 0, n - 1);

    }

    private ListNode dfs(ListNode[] lists, int l, int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return null;
        }
        int mid = (l + r) / 2;
        ListNode p =dfs(lists, l, mid);
        ListNode q = dfs(lists, mid + 1, r);
        return merge(p, q);
    }

    private ListNode merge(ListNode p, ListNode q) {
        if (p == null || q == null) {
            return p == null ? q : p;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head;
        while (p != null && q != null) {
            if (p.val <= q.val) {
                tail.next = p;
                p = p.next;
            } else {
                tail.next = q;
                q = q.next;
            }
            //tail进行迭代
            tail = tail.next;
        }
        tail.next = p == null ? q : p;
        return head.next;
    }
}
